package com.chuang.bootplus.controller.storage.tencent;

import com.chuang.bootplus.base.exception.BusException;
import com.chuang.bootplus.base.utils.ApiResponse;
import com.chuang.bootplus.base.utils.ObjectUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.transfer.Download;
import com.qcloud.cos.transfer.TransferManager;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @description: TODO 腾讯云文件操作
 * @author nuo
 * @date 2022/5/12 0:21
 * @version 1.0
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class TencentServiceImpl implements TencentService {

    public final COSClient cosClient;
    public final TencentConfig tencentConfig;

    @Override
    public ApiResponse<Map<String, String>> upload(MultipartFile file) {

        if (ObjectUtil.isEmpty(file)) {
            throw new BusException("上传文件为空, 请选择后上传！");
        }

        try {
            String filename = file.getOriginalFilename();

            String bucketName = tencentConfig.getBucketName();

            String key = tencentConfig.getPrefix()
                    + UUID.randomUUID().toString().replaceAll("-", "")
                    + filename.substring(filename.lastIndexOf('.'));

            //将 MultipartFile 类型 转为 File 类型
            File localFile = File.createTempFile("temp", null);
            file.transferTo(localFile);

            cosClient.putObject(new PutObjectRequest(bucketName, key, localFile));
            Map<String, String> map = new HashMap<>(1);
            map.put("url", tencentConfig.getUrl() + key);
            return new ApiResponse<>(map);

        } catch (IOException e) {
            throw new BusException(e.getMessage());
        }

    }

    @Override
    public ApiResponse<String> download(String key, String path, String fileName) {
        TransferManager transferManager = null;
        try {
            //下载到本地指定路径
            File localDownFile = new File(path + fileName);
            GetObjectRequest getObjectRequest = new GetObjectRequest(tencentConfig.getBucketName(), tencentConfig.getPrefix() + key);
            // 下载文件
            transferManager = new TransferManager(cosClient);
            Download download = transferManager.download(getObjectRequest, localDownFile);
            // 等待传输结束 (如果想同步的等待上传结束，则调用 waitForCompletion)
            download.waitForCompletion();
        } catch (Throwable tb) {
            tb.printStackTrace();
            throw new BusException("下载失败...");
        } finally {
            // 关闭 TransferManger
            assert transferManager != null;
            transferManager.shutdownNow();
        }
        return new ApiResponse<>("下载成功...");
    }


    @Override
    public ApiResponse<Void> del(String key) {
        cosClient.deleteObject(tencentConfig.getBucketName(), tencentConfig.getPrefix() + key);
        return new ApiResponse<>();
    }

}
